# coding:utf-8
from typing import List, Dict

from fastapi import Query

from app.models.user import User
from app.admin.schemas.user import UserCreate, UserOutDB
from app.core.auth import get_password_hash


class UserService:
    # 列表
    async def page_list(self, query: Query, page: int = 1, limit: int = 10) -> List[UserOutDB]:
        start = (page - 1) * limit
        count = await User.filter(is_deleted=False).filter(query).count()
        lists = await User.filter(is_deleted=False).filter(query).offset(start).limit(limit).all()
        return count, lists

    async def get_id(self, item_id: int):
        item = await User.get_or_none(id=item_id)
        return item

    async def find(self, query: Query):
        item = await User.get_or_none(query)
        return item

    async def create(self, obj_in: UserCreate):
        if isinstance(obj_in, Dict):
            obj_dict = obj_in
        else:
            obj_dict = obj_in.model_dump()
        hash_pwd = get_password_hash(obj_in.password)
        obj_dict.update({"password": hash_pwd})
        item = await User.create(**obj_dict)
        return item

    async def update(self, obj_in: UserCreate):
        if isinstance(obj_in, Dict):
            obj_dict = obj_in
        else:
            obj_dict = obj_in.model_dump()
        print(obj_dict)
        # 删除键
        user_id = obj_dict.pop('id')
        user = await User.filter(id=user_id).update(**obj_dict)
        return user

    async def remove(self, item_id: int):
        user = await User.filter(id=item_id).first()
        if user:
            user.is_deleted = True
            await user.save()
            return True
        else:
            return False
